package com.rainbow.support.half.message.handler.consumer;

import com.rainbow.common.core.toolkit.ContextHolder;
import com.rainbow.common.core.toolkit.SpringBeanUtil;
import com.rainbow.support.half.message.entity.HalfMessagePayload;
import com.rainbow.support.half.message.handler.BaseHalfMsgHandler;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.lang.NonNull;

import java.util.Date;
import java.util.Objects;
import java.util.Optional;

/**
 * RocketMq消息消费者,统一验证以及存储消费者日志处理
 * 针对其他类型消息支持方便做消息消费者幂等性处理逻辑
 * @author rainbow
 */
public interface ValidateConsumerHandler extends BaseHalfMsgHandler {

    /**
     * MQ事务消费者,存储消费事务日志
     *
     * @param payload 消息载体
     * @param message 消息主体
     * @return 存储消费事务日志
     */
    default boolean saveConsumerLog(@NonNull HalfMessagePayload payload, @NonNull String message) {
        String consumerUserId= Optional.ofNullable(payload.getCreator()).orElse(ContextHolder.getUserId());
        Date consumerTime=Optional.ofNullable(payload.getCreateTime()).orElse(new Date());
        String insertSql = "INSERT INTO rocket_mq_consumer_log(branch_id,global_id,origin_body,create_time,creator,logic_delete) VALUES (?,?,?,?,?,?)";
        int total = Objects.requireNonNull(SpringBeanUtil.getBean(JdbcTemplate.class)).update(insertSql, payload.getBranchId(), payload.getGlobalId(), message, consumerTime,consumerUserId , false);
        return ObjectUtils.isNotEmpty(total) && total > 0;
    }

    /**
     * MQ事务消费者,检查消息主体分支事务id,是否已经存在
     *
     * @param branchId 消息主体分支事务id
     * @return 检查事务状态
     */
    default boolean checkBranchId(@NonNull String branchId) {
        Long total = Objects.requireNonNull(SpringBeanUtil.getBean(JdbcTemplate.class)).queryForObject(
                "select count(*) as total from rocket_mq_consumer_log where logic_delete=false and branch_id = ?",
                Long.class,
                branchId);
        return ObjectUtils.isNotEmpty(total) && total > 0;
    }
}
